﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CongThongTin.Entities;
using CongThongTin.Util;
using System.Text;

namespace CongThongTin.Administrators
{
    public partial class TinTuc : System.Web.UI.Page
    {
        CongThongTinEntities _entities;
       

        protected void Page_Load(object sender, EventArgs e)
        {
            _entities = new CongThongTinEntities();

            loadTinTuc();
            if (!IsPostBack)
            {
                loadTheLoaiTinTuc();
                loadLoaiTinTuc(Convert.ToInt32(ddlTenTheLoai.SelectedValue));
            }


            if (Request.QueryString["preview"] == "1" && !string.IsNullOrEmpty(Request.QueryString["fileId"]))
            {
                var fileId = Request.QueryString["fileId"];
                var fileContents = (byte[])Session["fileContents_" + fileId];
                var fileContentType = (string)Session["fileContentType_" + fileId];

                if (fileContents != null)
                {
                    Response.Clear();
                    Response.ContentType = fileContentType;
                    Response.BinaryWrite(fileContents);
                    Response.End();
                }
            }
        }

        protected void btnThemMoi_Click(object sender, EventArgs e)
        {
            try {

                int newMaTheLoai = int.Parse(ddlTenTheLoai.SelectedValue);
                Entities.THELOAI oNewTheLoai = _entities.THELOAIs.SingleOrDefault(tl=>tl.MATHELOAI==newMaTheLoai);

                int newMaLoaiTin = int.Parse(ddlTenLoai.SelectedValue);
                Entities.LOAITIN oNewLoaiTin = _entities.LOAITINs.SingleOrDefault(tl => tl.MALOAITIN == newMaLoaiTin);

                Entities.TINTUC oNewTinTuc = new TINTUC();
                oNewTinTuc.MATHELOAI = oNewTheLoai.MATHELOAI;
                oNewTinTuc.LOAITIN = oNewLoaiTin;
                oNewTinTuc.TIEUDE = tbTieuDe.Text.Trim();
                oNewTinTuc.TOMTAT = tbNoiDungTomTat.Text.Trim();
                StringBuilder nd = new StringBuilder(tbNoiDung.Text.Trim());
                nd.Replace("&lt;", "<");
                nd.Replace("&gt;", ">");
                oNewTinTuc.NOIDUNG = nd.ToString();
                oNewTinTuc.NGAYDANGTIN = DateTime.Now;
                oNewTinTuc.HIENTHI = true;
                //oNewTinTuc.TINNOIBAT = chkTinNoiBat.Checked;
                oNewTinTuc.HINHMOTA = Session[cGlobalUtil.STORED_IMAGE] as byte[]; 

                _entities.AddToTINTUCs(oNewTinTuc);
                _entities.SaveChanges();

                Response.Redirect(Page.Request.Url.ToString(),true);

                Session[cGlobalUtil.STORED_IMAGE] = null;
            }
            catch (Exception) { }
        }

        void loadLoaiTinTuc(int maTheLoai)
        {
            ddlTenLoai.DataSource = _entities.LOAITINs.Where(lt => lt.HIENTHI == true && lt.THELOAI.MATHELOAI == maTheLoai);
            ddlTenLoai.DataValueField = "MALOAITIN";
            ddlTenLoai.DataTextField = "TENLOAITIN";
            ddlTenLoai.DataBind();
            //btnThemMoi.Text = _entities.LOAITINs.Where(lt => lt.HIENTHI == true && lt.THELOAI.MATHELOAI == maTheLoai).Count().ToString();
        }
        void loadTheLoaiTinTuc()
        {
            ddlTenTheLoai.DataSource = _entities.THELOAIs.Where(tl=>tl.HIENTHI == true);
            ddlTenTheLoai.DataValueField = "MATHELOAI";
            ddlTenTheLoai.DataTextField = "TENTHELOAI";
            ddlTenTheLoai.DataBind();
        }
        void loadTinTuc()
        {
            var data = from tt in _entities.TINTUCs
                       select new { 
                            MaTinTuc=tt.MATINTUC,
                            TieuDe=tt.TIEUDE,
                            SoLanXem=tt.SOLANXEM,
                            TinNoiBat=tt.TINNOIBAT,
                            NGAYDANGTIN = tt.NGAYDANGTIN
                       };

            GridView1.DataSource = data;
            GridView1.DataBind();
        }

        protected void ddlTenTheLoai_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadLoaiTinTuc(Convert.ToInt32(ddlTenTheLoai.SelectedValue));
        }

        protected void ajaxFileUpload_OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
        {
            if (e.ContentType.Contains("jpg") || e.ContentType.Contains("gif")
                || e.ContentType.Contains("png") || e.ContentType.Contains("jpeg"))
            {
                Session["fileContentType_" + e.FileId] = e.ContentType;
                Session["fileContents_" + e.FileId] = e.GetContents();

                string fullPath = "/Images/" + e.FileName;

                // Save your File
                htmlEditorExtender2.AjaxFileUpload.SaveAs(Server.MapPath(fullPath));
                
                // Tells the HtmlEditorExtender where the file is otherwise it will render as: <img src="" />
                e.PostedUrl = fullPath;
                
            }

            // Set PostedUrl to preview the uploaded file.         
            //e.PostedUrl = string.Format("?preview=1&fileId={0}", e.FileId);

            
        }    

        protected void OnAsyncFileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            if (axAsyncFileUpload.PostedFile != null)
            {
                HttpPostedFile file = axAsyncFileUpload.PostedFile;

                byte[] data = ReadFile(file);
                Session[cGlobalUtil.STORED_IMAGE] = data;
            }
        }

        private byte[] ReadFile(HttpPostedFile file)
        {
            byte[] data = new Byte[file.ContentLength];
            file.InputStream.Read(data, 0, file.ContentLength);
            return data;
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            loadTinTuc();
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int id=int.Parse(e.CommandArgument.ToString());

            if (e.CommandName == "link2Update")
            {
                Response.Redirect("CapNhatTinTuc.aspx?matt="+e.CommandArgument);
            }
            if (e.CommandName == "link2Del")
            {
                TINTUC oDelTinTuc = _entities.TINTUCs.SingleOrDefault(t => t.MATINTUC == id);
                _entities.TINTUCs.DeleteObject(oDelTinTuc);
                _entities.SaveChanges();
                loadTinTuc();
            }
        }
    }
}